//
//  RootViewController.m
//  Together
//
//  Created by Wang Shuguang on 12-12-7.
//  Copyright (c) 2012年 Dawn. All rights reserved.
//

#import "RootViewController.h"
#import "RootCell.h"
#import "ItemsViewController.h"

#define DOWNLOADBTNTAG 2010
@interface RootViewController ()
- (void) update:(id)sender;
@end

@implementation RootViewController
@synthesize categoryArray;

- (void) dealloc{
    [categoryArray release];
    [progressDict release];
    [super dealloc];
}

- (id) init{
    if (self = [super init]) {
        self.categoryArray = [NSArray arrayWithContentsOfFile:RESOURCEFILE(@"API", @"plist")];
        progressDict = [[NSMutableDictionary alloc] init];
        for (int i = 0; i < self.categoryArray.count; i++) {
            NSDictionary *dict = (NSDictionary *)[self.categoryArray objectAtIndex:i];
            [progressDict setObject:[NSNumber numberWithFloat:0] forKey:[dict objectForKey:@"FileName"]];
        }
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    categoryTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MAINCONTENTHEIGHT)];
    [self.view addSubview:categoryTableView];
    [categoryTableView release];
    
    categoryTableView.rowHeight = 71;
    categoryTableView.delegate = self;
    categoryTableView.dataSource = self;
    categoryTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    // 背景色
    UIView *categoryBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MAINCONTENTHEIGHT)];
    UIImage *bgImage = [UIImage imageNamed:@"category_background.png"];
    categoryBgView.backgroundColor = [UIColor colorWithPatternImage:bgImage];

    categoryTableView.backgroundView = categoryBgView;
    [categoryBgView release];
    
    self.navigationItem.title = @"Together";
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:206.0/255.0 green:0 blue:7.0/255.0 alpha:1];
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"全部更新"
                                                                               style:UIBarButtonItemStylePlain
                                                                              target:self
                                                                              action:@selector(update:)] autorelease];
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"清除缓存"
                                                                               style:UIBarButtonItemStylePlain
                                                                              target:self
                                                                              action:@selector(clearCache:)] autorelease];
    
    
    
    [self showCache];
}

- (void) update:(id)sender{
    for (int i = 0; i < self.categoryArray.count; i++) {
        [self download:i];
    }
   
}

- (void) clearCache:(id)sender{
    [Common clearCache];
    [self showCache];
}

- (void) showCache{
    // 计算缓存大小
    self.navigationItem.leftBarButtonItem.title = [NSString stringWithFormat:@"清理%.2fM",[Common cacheSize]/1024.0f/1024.0f];
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.categoryArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dict = (NSDictionary *)[self.categoryArray objectAtIndex:indexPath.row];
    
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    long long updateTimeInterval = [[userDefaults objectForKey:[NSString stringWithFormat:@"%@_UpdateTime",[dict objectForKey:@"FileName"]]] longLongValue];
    
    NSDate *updateTime = [NSDate dateWithTimeIntervalSince1970:updateTimeInterval];
    NSString *key = nil;
    if (updateTime && updateTimeInterval) {
        key = [Common dateSwitchFromDate:updateTime];
    }else{
        key = nil;
    }
    
    
    RootCell *cell = (RootCell *)[tableView dequeueReusableCellWithIdentifier:@"RootCell"];
    if (!cell) {
        cell = [[[RootCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RootCell"] autorelease];
    }
    
    //cell.textLabel.text = [dict objectForKey:@"Title"];
    [cell setIconWithName:[dict objectForKey:@"Icon"]];
    if (indexPath.row == 0) {
        [cell setSeparateViewHidden:YES];
    }else{
        [cell setSeparateViewHidden:NO];
    }
    [cell setTitle:[dict objectForKey:@"Title"]];
    if (key) {
        [cell setUpdateTime:[NSString stringWithFormat:@"%@更新",key]];
    }else{
        [cell setUpdateTime:[NSString stringWithFormat:@"尚未更新"]];
    }
    
    float progress = [[progressDict objectForKey:[dict objectForKey:@"FileName"]] floatValue];
    
    [cell setProgress:progress];
    
    if (progress <=0 || progress >=1) {
        cell.downloadBtn.hidden = NO;
    }else{
        cell.downloadBtn.hidden = YES;
    }
    
    cell.src = [dict objectForKey:@"API"];
    [cell.downloadBtn addTarget:self action:@selector(downloadBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.downloadBtn.tag = indexPath.row + DOWNLOADBTNTAG;
    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dict = (NSDictionary *)[self.categoryArray objectAtIndex:indexPath.row];
    ItemsViewController *itemsVC = [[ItemsViewController alloc] initWithDict:dict];
    [self.navigationController pushViewController:itemsVC animated:YES];
    [itemsVC release];
//    if (indexPath.row == 0) {
//        BdjViewController *bdjVC = [[BdjViewController alloc] initWithDict:dict];
//        [self.navigationController pushViewController:bdjVC animated:YES];
//        [bdjVC release];
//    }else if (indexPath.row == 1) {
//        BdjmmViewController *bdjmmVC = [[BdjmmViewController alloc] initWithDict:dict];
//        
//        [self.navigationController pushViewController:bdjmmVC animated:YES];
//        [bdjmmVC release];
//    }else {
//        NetEasyViewController *netEasyVC = [[NetEasyViewController alloc] initWithDict:dict];
//        [self.navigationController pushViewController:netEasyVC animated:YES];
//        [netEasyVC release];
//    }
}



- (void) downloadBtnClick:(id)sender{
    UIButton *button = (UIButton *)sender;
    button.hidden = YES;
    [self download:button.tag - DOWNLOADBTNTAG];
}

- (void) download:(NSInteger)index{
    NSDictionary *dict = (NSDictionary *)[self.categoryArray objectAtIndex:index];
    NSString *url = [dict objectForKey:@"API"];
    NSString *getUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NewsRequest *request = [NewsRequest requestWithURL:[NSURL URLWithString:getUrl]];
    request.index = index;
    request.delegate = self;
    request.saveName = [dict objectForKey:@"FileName"];
    
    switch (request.index) {
        case 0:
            request.newsType = Budejie_Download;
            break;
        case 1:
            request.newsType = BudejieMM_Download;
            break;
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
            request.newsType = NetEasyHeadline_Download;
            break;
        case 7:
        case 8:
        case 9:
        case 10:
            request.newsType = Qiubai_Download;
            break;
        default:
            
            break;
    }
    [request startRequest];
    [progressDict setObject:[NSNumber numberWithFloat:0] forKey:request.saveName];
}

#pragma mark -
#pragma mark NewsRequestDelegate
- (void) requestFailed:(NewsRequest *)request{
    NSDictionary *dict = (NSDictionary *)[self.categoryArray objectAtIndex:request.index];
    [progressDict setObject:[NSNumber numberWithFloat:0.0f] forKey:[dict objectForKey:@"FileName"]];
    [categoryTableView reloadData];
}

- (void) requestFinished:(NewsRequest *)request withData:(NSDictionary *)dt{
    NSDictionary *dict = (NSDictionary *)[self.categoryArray objectAtIndex:request.index];
    [progressDict setObject:[NSNumber numberWithFloat:1.0f] forKey:[dict objectForKey:@"FileName"]];
     [categoryTableView reloadData];
    [self showCache];
}

- (void) requestProgress:(float)progress request:(NewsRequest *)request{
    NSDictionary *dict = (NSDictionary *)[self.categoryArray objectAtIndex:request.index];
   [progressDict setObject:[NSNumber numberWithFloat:progress] forKey:[dict objectForKey:@"FileName"]];
    [categoryTableView reloadData];
}
@end
